package org.vacoor.nothing.security.controller;

import com.google.common.base.Stopwatch;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.vacoor.nothing.security.lucene.GoodsSearchService;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 */
@Controller
@RequestMapping("/")
public class SolrSearchController {
    @Autowired
    private GoodsSearchService searchService;

    @RequestMapping
    public String index() {
        return "/layout";
    }

    @RequestMapping("/search")
    public String search(String q,
                         String cat,
                         String brand,
                         Double sPrice,
                         Double ePrice,
                         String[] prop,
                         @RequestParam(defaultValue = "0") int offset,
                         @RequestParam(defaultValue = "30") int rows,
                         String[] sort,
                         Map<String, Object> model) throws SolrServerException {
        rows = 0 < rows ? rows : 10;
        rows = 3000 > rows ? rows : 3000;

        Stopwatch watch = Stopwatch.createStarted();
        try {
            Map<String, Object> ret = searchService.search(q, cat, brand, sPrice, ePrice, prop, offset, rows, sort);
            System.out.println(String.format("查询用时 %s ms", watch.stop().elapsed(TimeUnit.MILLISECONDS)));

            model.putAll(ret);
            SolrDocumentList results = (SolrDocumentList) ret.get("results");
            long total = null != results ? results.getNumFound() : 0;
            model.put("numFound", total);
            if (1 > total) {
                return "/none";
            }

        } catch (Exception e) {
            e.printStackTrace();
            // TODO 为了排版，暂时忽略
            return "/none";
        }
        return "/search";
    }
}
